package com.tre.jdevtemplateboot.common.util;

import org.codehaus.plexus.util.StringUtils;
import org.slf4j.MDC;

/**
 * @author JDev
 */
public class TraceIdUtil {

    public static final  String TRACE_ID = "TRACE_ID";

    private TraceIdUtil(){

    }

    public static void initTrace() {
        if (StringUtils.isBlank(MDC.get(TRACE_ID))) {
            String traceId = generateTraceId();
            setTraceId(traceId);
        }
    }

    public static void clearTrace() {
        MDC.clear();
    }

    private static void setTraceId(String traceId) {
        traceId = StringUtils.left(traceId, 36);
        MDC.put(TRACE_ID, traceId);
    }

    private static String generateTraceId() {
        return String.valueOf(IdWorkerUtils.getInstance().nextId());
    }
}
